package com.xthink.web.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.xthink.common.result.AjaxResult;
import com.xthink.common.utils.RedisCache;
import com.xthink.web.service.SendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin //跨域的支持
public class SendSmsController {
    @Autowired
    private SendSmsService sendSmsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/send/{phone}")
    public AjaxResult send(@PathVariable("phone") String phone){
        //调用方法
        //生成验证码并存储到redis中
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long l = snowflake.nextId();
        String s = Long.toString(l);
        String code = s.substring(s.length() - 6);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);

        boolean isSend = sendSmsService.send(phone, "模板ID", param);

        if (isSend){
            redisCache.setCacheObject(phone,code,5,TimeUnit.SECONDS);
            return AjaxResult.success("验证码已发送成功");

        }else {
            return AjaxResult.error("验证码发送失败");
        }

    }
}
